'use strict';

// const { exec: spawn } = require('@imooc-cli-dev/utils');
const path = require("path")
const Package = require("@wss-cli-dev/package")
const log = require("@wss-cli-dev/log")
const cp = require('child_process')
const SETING_PATH = {
  init: "@wss-cli-dev/init"
}
const CACHE_DIR = "dependencies"


async function exec(name, options, command) {
  // 1. TARGET_PATH targetPath 获取targetPath
  let targetPath = process.env.CLI_TARGET_PATH
  const homePath = process.env.CLI_HOME_PATH
  const packageName = SETING_PATH[name]
  const packageVersion = "latest"
  let storeDir = ""
  let pkg
  // 2. modelspath 指向
  // 当路径不存在时候执行
  if (!targetPath) {
    targetPath = path.resolve(homePath, CACHE_DIR)
    storeDir = path.resolve(targetPath, "node_modules")
    log.verbose(targetPath)
    log.verbose(storeDir)
    pkg = new Package({
      targetPath,
      packageName,
      packageVersion,
      storeDir
    })
    if (await pkg.exists()) {
      // 更新
      console.log("更新package");
      await pkg.update()
    } else {
      await pkg.install()
    }
  } else {
    // 4. 当路径存在时候执行
    pkg = new Package({
      targetPath,
      packageName,
      packageVersion,
    })
  }

  // 3. 获取入口文件
  const rootFile = pkg.getRootFilePath()
  if (rootFile) {
    try {
      // node 进程 
      // require(rootFile).call(null, Array.from(arguments))
      let args = Array.from(arguments)
      let cmd = args[args.length - 1]
      let obj = Object.create(null)
      Object.keys(cmd).forEach(key => {
        if (cmd.hasOwnProperty(key)) {
          obj[key] = cmd[key];
        }
      })
      const code = `require('${rootFile}').call(null, ${JSON.stringify(args)})`;
      // 子进程
      const child = spawn('node', ['-e', code], {
        cwd: process.cwd(),
        stdio: 'inherit',
      });
      child.on("error", (e) => {
        log.error(e.message)
        process.exit(1)
      })
      child.on("exit", (e) => {
        log.verbose("命令执行成功：")
        process.exit(0)
      })
    } catch (error) {
      log.error(error.message)
    }
  }
  function spawn(command, args, options) {
    const win32 = process.platform === 'win32';

    const cmd = win32 ? 'cmd' : command;
    const cmdArgs = win32 ? ['/c'].concat(command, args) : args;

    return cp.spawn(cmd, cmdArgs, options || {});
  }
}
module.exports = exec;
